const navMenu = document.querySelector('#nav-menu')
const navToggle = document.querySelector('#nav-toggle')
const navClose = document.querySelector('#nav-close')


// nav-toggle存在
if (navToggle) {
  navToggle.addEventListener('click', () => {
    // 展示菜单
    navMenu.classList.add('show-menu')
  })
}

if (navClose) {
  navClose.addEventListener('click', () => {
    // 隐藏菜单
    navMenu.classList.remove('show-menu')
  })
}

// 移除菜单
const navLink = document.querySelectorAll('.nav-link')

function linkAction() {
  const navMenu = document.querySelector('#nav-menu')
  navMenu.classList.remove('show-menu')
}

navLink.forEach(link => link.addEventListener('click', linkAction))

// home 轮播图
let homeSwiper = new Swiper(".home-swiper", {
  spaceBetween: 30,
  loop: 'true',

  pagination: {
    el: ".swiper-pagination",
    clickable: true,
  }
})

// 改变头部背景颜色
function scrollHeader() {
  const header = document.getElementById('header')
  // When the scroll is greater than 50 viewport height, add the scroll-header class to the header tag
  if (this.scrollY >= header.offsetHeight) {
    header.classList.add('scroll-header')
  } else {
    header.classList.remove('scroll-header')
  }
}
window.addEventListener('scroll', scrollHeader)

// new 轮播图
let newSwiper = new Swiper(".new-swiper", {
  centeredSlides: true,
  slidesPerView: "auto",
  loop: 'true',
  spaceBetween: 16
})

// 滚动 sections 链接高亮
const sections = document.querySelectorAll('section[id]')

function scrollActive() {
  // 只读属性
  const scrollY = window.pageYOffset

  sections.forEach(current => {
    const sectionHeight = current.offsetHeight
    const sectionTop = current.offsetTop - 58
    const sectionId = current.getAttribute('id')

    if (scrollY > sectionTop && scrollY <= sectionTop + sectionHeight) {
      document.querySelector('.nav-menu a[href*=' + sectionId + ']').classList.add('active-link')
    } else {
      document.querySelector('.nav-menu a[href*=' + sectionId + ']').classList.remove('active-link')
    }
  })
}

window.addEventListener('scroll', scrollActive)

// 返回顶部
function scrollUp() {
  const scrollUp = document.getElementById('scroll-up')
  if (this.scrollY >= 460) {
    scrollUp.classList.add('show-scroll')
  } else {
    scrollUp.classList.remove('show-scroll')
  }
}
window.addEventListener('scroll', scrollUp)


// 动画
const sr = ScrollReveal({
  origin: 'top',
  distance: '60px',
  duration: 2500,
  delay: 400,
  reset: true
})

sr.reveal(`.home-swiper, .new-swiper, .newsletter-container`)
sr.reveal(`.about-data, .discount-img`, { origin: 'left' })
sr.reveal(`.about-img, .discount-data`, { origin: 'right' })
sr.reveal(`.category-data, .trick-content, .footer-content`, { interval: 200 })